import { defineComponent, ref, reactive, computed } from "vue";
import styles from "./popupMenu.module.less";
export default defineComponent({
  props: {
    itemList: {
      type: Array,
      default: () => [],
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:visible', 'select'],
  setup(props, { emit }) {
    const state = reactive({
      left: 0,
      top: 0,
      target: null,
      meta: null,
    } as {
      left: number;
      top: number;
      target: any;
      meta: any;
    });
    const selectedKeys = ref([]);
    const style = computed(() => {
      return {
        left: state.left + 'px',
        top: state.top + 'px'
      }
    });
    const handleClick = ({ key }: any) => {
      emit('select', {key,target: state.target, meta: state.meta});
      closeMenu();
    }
    const popupMenu = () => (
      props.visible ? <a-menu
        class={styles.contextmenu}
        style={style.value}
        selectedKeys={selectedKeys.value}
        onClick={(e: any) => handleClick(e)}
      >
        {
          props.itemList.map((x: any) => (
            <a-menu-item key={x.key}>
              <span>{x.text}</span>
            </a-menu-item>
          ))
        }
      </a-menu> : <div></div>
    );
    const closeMenu = () => {
      emit('update:visible', false);
    };
    const setPosition = (e: any) => {
      state.left = e.clientX;
      state.top = e.clientY;
      state.target = e.target;
      state.meta = e.meta;
    };
    return {
      closeMenu,
      setPosition,
      popupMenu,
    };
  },
  created() {
    window.addEventListener('click', this.closeMenu);
    window.addEventListener('contextmenu', this.setPosition);
  },
  beforeDestroy() {
    window.removeEventListener('click', this.closeMenu);
    window.removeEventListener('contextmenu', this.setPosition);
  },
  render() {
    return <this.popupMenu></this.popupMenu>;
  },
})